package com.qst.order.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qst.order.domain.UserAddress;
import com.qst.order.mapper.UserAddressMapper;
import com.qst.order.service.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {

    @Autowired
    private UserAddressMapper userAddressMapper;
    @Override
    public List<UserAddress> getAddressByUserId(Integer userId) {
     return   userAddressMapper.getAddressByUserId(userId);
    }

    @Override
    public UserAddress updateAddress(UserAddress address) {
        // 1. 执行更新操作（返回受影响的行数）
        int rows = userAddressMapper.updateById(address);

        // 2. 校验更新是否成功（如果受影响行数为0，说明地址不存在或未修改）
        if (rows <= 0) {
            throw new RuntimeException("地址更新失败，地址不存在或数据未变更");
        }

        // 3. 通过主键查询更新后的最新数据返回

         return userAddressMapper.selectById(address.getId());
    }

    @Override
    public UserAddress saveAddress(UserAddress address) {
        int insert = userAddressMapper.insert(address);
        if (insert <= 0) {
            throw new RuntimeException("地址更新失败，地址不存在或数据未变更");
        }
        // 3. 通过主键查询更新后的最新数据返回
        return userAddressMapper.selectById(address.getId());
    }

}